package com.woniuxy.controller;

import com.woniuxy.commons.BaseServlet;
import com.woniuxy.commons.JDKProxy;
import com.woniuxy.model.City;
import com.woniuxy.service.CityService;
import com.woniuxy.service.UserService;
import com.woniuxy.service.imp.CityServiceImpl;
import com.woniuxy.service.imp.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/m")
public class MainServlet extends BaseServlet {


    public String login(HttpServletRequest req, HttpServletResponse resp){
        String userName = req.getParameter("userName");
        String pwd = req.getParameter("pwd");
        UserService proxy = new JDKProxy<UserService>().getProxy(new UserServiceImpl());
        String login = proxy.login(userName, pwd);
        if (login==null){
            req.setAttribute("log","有问题");
            return "f:/index.jsp";
        }
        if (login.equals("登陆成功！")){
            req.getSession().setAttribute("user",userName);
            return "r:/m?method=city";
        }else{
            req.setAttribute("log",login);
            return "f:/index.jsp";
        }

    }

    public String city(HttpServletRequest req, HttpServletResponse resp){
        CityService proxy = new JDKProxy<CityService>().getProxy(new CityServiceImpl());
        List<City> cities = proxy.getCities();
        System.out.println(cities);
        req.getSession().setAttribute("cities",cities);
        return "r:/cities.jsp";
    }

    public String delete(HttpServletRequest req, HttpServletResponse resp){
        CityService proxy = new JDKProxy<CityService>().getProxy(new CityServiceImpl());
        List<Integer> ids = new ArrayList<>();
        String[] boxes = req.getParameterValues("box");
        for (String box : boxes) {
            ids.add(Integer.valueOf(box));
        }
        proxy.deleteCities(ids);
        return "f:/m?method=city";
    }
}
